#pragma once
#include <iostream>
#include <vector>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

#define ERR_EXIT(m)         \
    do                      \
    {                       \
        perror(m);          \
        exit(EXIT_FAILURE); \
    } while (0)

#define FIFO_NAME "fifo"

class NamedFifo
{
public:
    NamedFifo(const std::string&path):_path_name(path)
    {
    }
    void CreatFifo()
    {
        umask(0);
        int n=mkfifo(_path_name.c_str(),0666);
        if(n<0)
        {
            ERR_EXIT("mkfifo error");
        }
        else
        {
            std::cout<<"mkfifo success"<<std::endl;
        }
    }
    void DeleteFifo()
    {
        int n=unlink(_path_name.c_str());
        if(n<0)
        {
            ERR_EXIT("unlink error");
        }
        else
        {
            std::cout<<"unlink success"<<std::endl;
        }
    }

    void OpenWriter()
    {
        _fd=open(_path_name.c_str(),O_WRONLY);
        if(_fd<0)
        {
            ERR_EXIT("OpenWriter error");
        }
        else
        {
            std::cout<<"OpenWriterk success"<<std::endl;
        }
    }

    void OpenReader()
    {
        _fd=open(_path_name.c_str(),O_RDONLY);
        if(_fd<0)
        {
            ERR_EXIT("OpenReader error");
        }
        else
        {
            std::cout<<"OpenReader success"<<std::endl;
        }
    }

    void Close()
    {
        close(_fd);
    }

    void Write()
    {
        std::string buffer;
        while(true)
        {
            std::cout<<"Please Enter#";
            std::getline(std::cin,buffer);
            int n=write(_fd,buffer.c_str(),buffer.size());
            if(n<0)
            {
                ERR_EXIT("write error");
            }
        }
    }

    void Read()
    {
        char buffer[1024];
        while(true)
        {
            int n=read(_fd,buffer,sizeof(buffer)-1);
            if(n<0)
            {
                ERR_EXIT("read error");
            }
            else if(n==0)
            {
                std::cout<<"client quit,me too"<<std::endl;
                break;
            }
            else
            {
                buffer[n]=0;
                std::cout<<"client say:"<<buffer<<std::endl;
            }
        }
    }

private:
    std::string _path_name;
    int _fd;
};